#include "QDetachEdgeOperation.h"

#include "Core/MainWindow.h"
#include "Core/RWGeometryTool.h"
#include <TopoDS.hxx>
#include <QMessageBox>

#include "FeatureShape/ShapeOperation.h"
#include "FeatureShape/HistoryManager.h"

QDetachEdgeOperation::QDetachEdgeOperation(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QDetachEdgeOperationClass())
{
	ui->setupUi(this);

	m_mainWindow->SetCanMultiSelect(false);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QDetachEdgeOperation::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QDetachEdgeOperation::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QDetachEdgeOperation::close);

	connect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QDetachEdgeOperation::OnSelectedSubShapes);

	m_mainWindow->SetSelectionMode(SM_Edge);
}

QDetachEdgeOperation::~QDetachEdgeOperation()
{
	delete ui;
}

void QDetachEdgeOperation::OnSelectedSubShapes(QIVtkSelectionPipeline* actor)
{	
	// #TODO:选择一个复合模型(多个wire), 理论上也可以进行 Detach, 所以需要完善一下:
	// 1. 首先判断选择的actor是否有效
	// 2. 找到这个edge所属的wire，进行detach
	// 3. 若这个edge是一个孤立边，直接 Detach 即可
	// 对wire才能进行边拆分
	if (actor->OccShape().ShapeType() == TopAbs_WIRE)
	{
		m_selectedActor = actor;
	}
}

void QDetachEdgeOperation::closeEvent(QCloseEvent* event)
{
	disconnect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QDetachEdgeOperation::OnSelectedSubShapes);

	m_mainWindow->SubWidgetClose(bIsConfirmed);
	m_mainWindow->SetCanMultiSelect(true);
}

void QDetachEdgeOperation::OnModify()
{
	DetachInner();
	m_selectedActor = nullptr;
}

void QDetachEdgeOperation::OnConfirm()
{
	DetachInner();
	close();
}

void QDetachEdgeOperation::DetachInner()
{
	if (!m_selectedActor)
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	TopoDS_Wire wire = TopoDS::Wire(m_selectedActor->OccShape());
	TopoDS_Edge edge = TopoDS::Edge(m_mainWindow->GetSelectedShapes()[0]);
	TopoDS_Shape remain;

	if (!RemoveEdgeFromWire(wire, edge, remain))
	{
		return;
	}

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);
	int subShapeIndex = GetSubShapeIndex(m_selectedActor->OccShape(), TopAbs_EDGE, edge);

	DetachEdgeOperation* op = new DetachEdgeOperation(QString("Detach Edge"), shapeIndex, subShapeIndex);
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	m_mainWindow->RemoveActorFromRenderer(m_selectedActor);
	m_mainWindow->createBasicUnitActor(remain, true);
	m_mainWindow->createBasicUnitActor(edge, true);
}
